package com.nulldev.util.net.inetplus;

import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;

import com.nulldev.util.net.inetplus.IInetAddress.DNSSource;
import com.nulldev.util.net.inetplus.IInetAddress.DNSSource.DNSSourceMeta;
import com.nulldev.util.other.ArrayUtils;

public class IInetDNSManager {

	public static interface DefaultDNS {
		
		public static final DNSSource GOOGLE_DNS_PRIMARY = new DNSSource(IInetAddress.createUnresolved("8.8.8.8"),
				new DNSSourceMeta("Google DNS"));
		public static final DNSSource GOOGLE_DNS_SECONDARY = new DNSSource(IInetAddress.createUnresolved("8.8.4.4"),
				new DNSSourceMeta("Google DNS [Alternate]"));
		
		public static final DNSSource FreeDNS = new DNSSource(IInetAddress.createUnresolved("37.235.1.174"), 
				new DNSSourceMeta("FreeDNS", false));
		public static final DNSSource FreeDNS_SECONDARY = new DNSSource(IInetAddress.createUnresolved("37.235.1.177"), 
				new DNSSourceMeta("FreeDNS [Alternate Source]", false));
		
		public static final DNSSource CLOUDFLARE_DNS = new DNSSource(IInetAddress.createUnresolved("1.1.1.1"),
				new DNSSourceMeta("Cloudflare 1.1.1.1"));
		
		public static final DNSSource UncensoredDNS = new DNSSource(IInetAddress.createUnresolved("91.239.100.100"), true, 
				new DNSSourceMeta("Uncensored DNS", false));
		public static final DNSSource UncensoredDNS_SECONDARY = new DNSSource(IInetAddress.createUnresolved("89.233.43.71"), true,
				new DNSSourceMeta("Uncensored DNS: Alternate Source", false));
		
		public static final DNSSource[] SOURCES = {
			UncensoredDNS,
			UncensoredDNS_SECONDARY,
			FreeDNS,
			FreeDNS_SECONDARY,
			GOOGLE_DNS_PRIMARY,
			GOOGLE_DNS_SECONDARY,
			CLOUDFLARE_DNS,
		};
	}
	
	private static final CopyOnWriteArrayList<DNSSource> DNS_SOURCES = new CopyOnWriteArrayList<DNSSource>();
	
	static {
		if (DNS_SOURCES.isEmpty()) {
			DNS_SOURCES.addAll(ArrayUtils.toArrayList(DefaultDNS.SOURCES));
		}
	}
	
	public static void defaults() {
		DNS_SOURCES.clear();
		if (DNS_SOURCES.isEmpty()) {
			DNS_SOURCES.addAll(ArrayUtils.toArrayList(DefaultDNS.SOURCES));
		}
	}
	
	public static void set(final DNSSource[] sources) {
		if (sources == null || sources.length == 0) {
			return;
		}
		DNS_SOURCES.clear();
		if (DNS_SOURCES.isEmpty()) {
			DNS_SOURCES.addAll(ArrayUtils.toArrayList(sources));
		}
	}
	
	public static DNSSource primary() {
		return ArrayUtils.first(DNS_SOURCES);
	}
	
	public static DNSSource secondary() {
		try {
			return DNS_SOURCES.get(1);
		}catch (Exception e) {
			return random();
		}
	}
	
	public static DNSSource random() {
		return ArrayUtils.random(DNS_SOURCES);
	}
}
